package com.distribute.application.api.rest.member;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.weaver.ast.Var;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.distribute.application.api.BaseApiController;
import com.distribute.application.api.utils.Arith;
import com.distribute.application.api.utils.IpUtil;
import com.distribute.application.api.utils.MapHelper;
import com.distribute.application.api.utils.PayUtil;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.title;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.model.Account;
import com.distribute.framework.model.Agent;
import com.distribute.framework.model.BalanceDetails;
import com.distribute.framework.model.BindingDistributor;
import com.distribute.framework.model.BrandAccount;
import com.distribute.framework.model.Commodity;
import com.distribute.framework.model.Configur;
import com.distribute.framework.model.Coupon;
import com.distribute.framework.model.DirectOrder;
import com.distribute.framework.model.Distributor;
import com.distribute.framework.model.DistributorIncome;
import com.distribute.framework.model.IncomeRecord;
import com.distribute.framework.model.Member;
import com.distribute.framework.model.Merchant;
import com.distribute.framework.model.OrderDetails;
import com.distribute.framework.model.Parameter;
import com.distribute.framework.model.Product;
import com.distribute.framework.model.ProductDetails;
import com.distribute.framework.model.ProductOrder;
import com.distribute.framework.model.Region;
import com.distribute.framework.model.TbBalanceStatistics;
import com.distribute.framework.model.TbJxsh;
import com.distribute.framework.model.TbJxshIncome;
import com.distribute.framework.model.TbMsg;
import com.distribute.framework.model.ProductOrder.Details;
import com.distribute.framework.model.TbOrderInvoies;
import com.distribute.framework.model.TbPartnerIncome;
import com.distribute.framework.model.TbPartners;
import com.distribute.framework.model.UserAddress;
@RestController(value="api.MemberOrderController")
public class MemberOrderController  extends BaseApiController{
	/**
	 * 会员取消订单
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/cancelOrder.do")
	public @title("会员取消订单") Protocol cancelOrder(
			@title("订单ID") Long id
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder order=DirectOrder.where.id(id).get();
		if (order!=null) {
			order.setStatus((short)7);
			order.update();
			protocol.set("type", 1);
			protocol.set("msg", "取消成功");
		}else {
			protocol.set("type", 2);
			protocol.set("msg", "订单不存在");
		}
		return protocol;
	}
	/**
	 * 会员删除自己的订单
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/delOrder.do")
	public @title("会员删除自己的订单") Protocol delOrder(
			@title("订单ID") Long id
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder order=DirectOrder.where.id(id).get();
		if (order!=null) {
			order.setStatus((short)7);
			order.update();
			protocol.set("type", 1);
			protocol.set("msg", "删除成功");
		}else {
			protocol.set("type", 2);
			protocol.set("msg", "订单不存在");
		}
		return protocol;
	}
	
	/**
	 * 会员确认收货
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/getGoodsOk.do")
	public @title("会员确认收货") Protocol getGoodsOk(
			@title("订单ID") Long id
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder order=DirectOrder.where.id(id).get();
		if (order==null) {
			protocol.set("type", 2);
			protocol.set("msg", "订单不存在");
			return protocol;
		}
		    if (order.getOrderType()==1) {
				if (order.getUseProductVouchers()!=null&&order.getUseProductVouchers().equals("")) {
					JSONArray daArray=JSONArray.parseArray(order.getUseProductVouchers());
					for (int i = 0; i < daArray.size(); i++) {
						JSONObject jsonObject=daArray.getJSONObject(i);
						TbBalanceStatistics balanceStatistics=TbBalanceStatistics.where.tbbsBrand(order.getMerchant()).get();
						if (balanceStatistics!=null) {
							balanceStatistics.setTbbsNowMonthBuy(balanceStatistics.getTbbsNowMonthBuy()+Integer.valueOf(jsonObject.getInteger("count")));
							balanceStatistics.setTbbsNowMonthSurplus(balanceStatistics.getTbbsNowMonthSurplus()+Integer.valueOf(jsonObject.getInteger("count")));
							balanceStatistics.update();
						}else {
							TbBalanceStatistics statistics=new TbBalanceStatistics(
									order.getMerchant()//品牌
								 	,0//上月余量
								 	,Integer.valueOf(jsonObject.getInteger("count"))//本月购量
								 	,0//本月兑换
								 	,Integer.valueOf(jsonObject.getInteger("count"))//本月剩余
								 	,new Date()//修改时间
									);
							statistics.save();
						}
					}
				}
				
				List<OrderDetails> orderDetailss=OrderDetails.where.orders(order.getId()).list(100);
				if (orderDetailss.size()>0) {
					for (OrderDetails orderDetails : orderDetailss) {
						Commodity commodity=Commodity.where.id(orderDetails.getGoodsNumber()).get();
						commodity.setRaleVol(commodity.getRaleVol()+orderDetails.getNumber());
						commodity.update();
						if (order.getOrderType()==2) {
							TbBalanceStatistics balanceStatistics=TbBalanceStatistics.where.tbbsBrand(order.getMerchant()).get();
							if (balanceStatistics!=null) {
								balanceStatistics.setTbbsNowMonthBuy(balanceStatistics.getTbbsNowMonthBuy()+orderDetails.getNumber());
								balanceStatistics.setTbbsNowMonthSurplus(balanceStatistics.getTbbsNowMonthSurplus()+orderDetails.getNumber());
								balanceStatistics.update();
							}else {
								TbBalanceStatistics statistics=new TbBalanceStatistics(
										order.getMerchant()//品牌
									 	,0//上月余量
									 	,orderDetails.getNumber()//本月购量
									 	,0//本月兑换
									 	,orderDetails.getNumber()//本月剩余
									 	,new Date()//修改时间
										);
								statistics.save();
							}
						}
					}
				}
				order.setStatus((short)4);
				order.update();
				
				List<IncomeRecord> incomeRecords=IncomeRecord.where.orderNumber(order.getNo()).list(100);
				for (IncomeRecord incomeRecord : incomeRecords) {
					if (incomeRecord.getEndStatus()==(short)1) {
							Account tAccount=Account.where.member(incomeRecord.getBeneficiary()).get();
							if (tAccount!=null) {
								tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), incomeRecord.getIncome()), 2));//直接代理奖励
								 tAccount.update();
								 incomeRecord.setEndStatus((short)2);
								 incomeRecord.update();
								 TbMsg msg2=new TbMsg(
										 incomeRecord.getBeneficiary()//会员
		   	     						 	,"您获得了收益:"+incomeRecord.getIncome()//内容
		   	     						 	,new Date()//时间
		   	     							);
		   	                		msg2.save();	
							}
					}
				}
				
				 Parameter parameter=Parameter.where.merchant(order.getMerchant()).get();
				 Configur configur=Configur.where.status((short)1).get();
				 TbOrderInvoies orderInvoies=new TbOrderInvoies(
						 	
						    order.getNo()//订单编号
						 	,order.getOrderType()//来源
						 	,order.getMerchant()//品牌商
						 	,order.getMember()//购买人
						 	,order.getTotalSum()//订单总金额
						 	,order.getActualPay()//实际支付金额
						 	,order.getProductFree()//余额抵扣金额
						 	,order.getCouponFree()//优惠卷抵扣金额
						 	,Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), configur.getProfitRatio()), 2)//平台收益
						 	,0.0//普通间接收益
						 	,0.0//普通直接收益
						 	,0.0//代理间接收益
						 	,0.0//代理直接收益
						 	,0.0//合伙人收益
						 	,0.0//配送商收益
						 	,0.0//经销商收益
						 	,0.0
						 	,new Date()//添加时间
						 );
				    orderInvoies=orderInvoies.save();
				    if (member.gettTop()!=null&&!member.gettTop().equals("")) {
				    	Agent agent=Agent.where.member(Long.parseLong(member.gettTop())).merchant(order.getMerchant()).get();
				    	if (agent!=null) {
				    		orderInvoies.setTboiDlZj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpDlZj()), 2));
						}else {
							orderInvoies.setTboiPtZj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpPtZj()), 2));
						}
					}
				    if (member.gettToptop()!=null&&!member.gettToptop().equals("")) {
				    	Agent agent=Agent.where.member(Long.parseLong(member.gettToptop())).merchant(order.getMerchant()).get();
				    	if (agent!=null) {
				    		orderInvoies.setTboiDlJj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpDlJj()), 2));
						}else {
							orderInvoies.setTboiPtJj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpPtJj()), 2));
						}
					}
				    if (order.getDistributor()!=null) {
				    	Distributor distributor=Distributor.where.id(order.getDistributor()).get();
				    	if (distributor!=null) {
				    		DistributorIncome distributorIncome=DistributorIncome.where.directOrder(order.getId()).distributor(distributor.getId()).get();
				    		if (distributorIncome!=null&&distributorIncome.getOrderStatus()==(short)1) {
								orderInvoies.setTboiPsSy(Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()));
											 Account tAccount=Account.where.member(distributor.getMember()).get();
											 if (tAccount!=null) {
												 tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), distributorIncome.getDistriIncome()), 2));//直接代理奖励
												 tAccount.update();
												 distributorIncome.setOrderStatus((short)2);
												 distributorIncome.update();
												 TbMsg msg2=new TbMsg(
														 distributor.getMember()//会员
						   	     						 	,"您获得了收益:"+distributorIncome.getDistriIncome()//内容
						   	     						 	,new Date()//时间
						   	     							);
						   	                		msg2.save();	
											}
											
								}
				    	  	
				    		BindingDistributor bindingDistributor=BindingDistributor.where.merchant(order.getMerchant()).distributor(distributor.getId()).get();
							if (bindingDistributor!=null&&bindingDistributor.getBindingdJxsh()!=null) {
								TbJxsh jxs=TbJxsh.where.tbjId(bindingDistributor.getBindingdJxsh()).get();
								if (jxs!=null) {
									order.setJxs(jxs.getTbjName());
									order.update();
								}
							 orderInvoies.setTboiJxsSy(((Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()))*0.08)/0.18);
							 List<OrderDetails> orderDetails=OrderDetails.where.orders(order.getId()).list(-1);
							 List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
								for (OrderDetails orderDetails2 : orderDetails) {
									Map<String, Object> map=new HashMap<String, Object>();
									map.put("goodsNumber",orderDetails2.getGoodsNumber());
									map.put("name", orderDetails2.getName());
									map.put("price", orderDetails2.getPrice());
									map.put("number", orderDetails2.getNumber());
									map.put("status", orderDetails2.getStatus$());
									list.add(map);
								}								 TbJxshIncome jxshIncome=new TbJxshIncome(
										order.getMerchant()
										,bindingDistributor.getBindingdJxsh()//经销商
										,order.getJxs()
									 	,order.getId()//订单编号
									 	,order.getAddTime()
									 	,order.getConsigneeName()
									 	,order.getDistributor$()
									 	,order.getOrderType()
									 	,JSON.toJSONString(list)
									 	,((Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()))*0.08)/0.18
									 	//,Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpJxshYj(),order.getCouponFree())//收益金额
									 	,new Date()
										);
								jxshIncome.save();
							}
				    	}
					}
					
				 TbPartners partners=TbPartners.where.tbpJiedao(order.getStreet()).get();
				 Region region=Region.where.id(order.getStreet()).get();
				 if (partners!=null) {
					 Member member2=Member.where.uid(partners.getTbpMember()).get();
					 orderInvoies.setTboiHhrSy(Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpHhrYj(),order.getCouponFree()));
					 TbPartnerIncome partnerIncome=new TbPartnerIncome(
							     order.getMerchant()//品牌
							 	,member2.getUid()//会员
							 	,order.getNo()
								,order.getOrderType()
							 	,member2.getNickName()
							 	,member.getHeader()//头像
							 	,member.getNickName()//昵称
							 	,region.getName()//街道
							 	,region.get$parent().getFullName()
							 	,new Date()//下单时间
							    ,Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpHhrYj(),order.getCouponFree())//收益金额
							 );
					 partnerIncome.save();
					 Account tAccount=Account.where.member(member2.getUid()).get();
					 if (tAccount!=null) {
						 tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpHhrYj(),order.getCouponFree())), 2));//直接代理奖励
						 tAccount.update();
						 TbMsg msg2=new TbMsg(
								 member2.getUid()//会员
   	     						 	,"您获得了收益:"+Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpHhrYj(),order.getCouponFree())//内容
   	     						 	,new Date()//时间
   	     							);
   	                		msg2.save();	
					}
				}
				 orderInvoies.setTboiSySy(Arith.round(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(
						                                                         order.getTotalSum(), order.getDispatFee()),
						                                                         orderInvoies.getTboiPtSy()),
																				 orderInvoies.getTboiPtJj()),
																				 orderInvoies.getTboiPtZj()),
																				 orderInvoies.getTboiDlJj()),
																				 orderInvoies.getTboiDlZj()),
																				 orderInvoies.getTboiPsSy()),
																				 orderInvoies.getTboiHhrSy()),
																				 orderInvoies.getTboiJxsSy()), 2));
				orderInvoies.update(); 
				BrandAccount brandAccount=BrandAccount.where.brand(order.getMerchant()).get();
				if (brandAccount==null) {
					BrandAccount bccount=new BrandAccount(
							order.getMerchant()//所属品牌 [非空]
						 	,orderInvoies.getTboiSySy()//总金额
						 	,orderInvoies.getTboiSySy()//累计收益
						 	,0.0//累计提现
						 	,new Date()//修改时间 [非空]
						 	,new Date()//添加时间 [非空]
						 	,(short)1//状态 [非空]
							);
					bccount.save();
				}else {
					brandAccount.setMoney(Arith.round(Arith.add(brandAccount.getMoney(), orderInvoies.getTboiSySy()), 2));
					brandAccount.setlSmoney(Arith.round(Arith.add(brandAccount.getlSmoney(), orderInvoies.getTboiSySy()), 2));
					brandAccount.update();
				}
				
			}else {
				//余额提货
				List<OrderDetails> orderDetailss=OrderDetails.where.orders(order.getId()).list(100);
				Parameter parameter=Parameter.where.merchant(order.getMerchant()).get();
				double gj=0.0;
				if (orderDetailss.size()>0) {
					for (OrderDetails orderDetails : orderDetailss) {
						Commodity commodity=Commodity.where.id(orderDetails.getGoodsNumber()).get();
						commodity.setRaleVol(commodity.getRaleVol()+orderDetails.getNumber());
						commodity.update();
						if (order.getOrderType()==2) {
							TbBalanceStatistics balanceStatistics=TbBalanceStatistics.where.tbbsBrand(order.getMerchant()).get();
							if (balanceStatistics!=null) {
								balanceStatistics.setTbbsNowMonthBuy(balanceStatistics.getTbbsNowMonthBuy()+orderDetails.getNumber());
								balanceStatistics.setTbbsNowMonthSurplus(balanceStatistics.getTbbsNowMonthSurplus()+orderDetails.getNumber());
								balanceStatistics.update();
							}else {
								TbBalanceStatistics statistics=new TbBalanceStatistics(
										order.getMerchant()//品牌
									 	,0//上月余量
									 	,orderDetails.getNumber()//本月购量
									 	,0//本月兑换
									 	,orderDetails.getNumber()//本月剩余
									 	,new Date()//修改时间
										);
								statistics.save();
							}
						}
						
						gj=gj+orderDetails.getNumber()*orderDetails.getPrice()*0.7;
					}
				}
				order.setStatus((short)4);
				order.update();
				
				List<IncomeRecord> incomeRecords=IncomeRecord.where.orderNumber(order.getNo()).list(100);
				for (IncomeRecord incomeRecord : incomeRecords) {
					if (incomeRecord.getEndStatus()==(short)1) {
							Account tAccount=Account.where.member(incomeRecord.getBeneficiary()).get();
							if (tAccount!=null) {
								tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), incomeRecord.getIncome()), 2));//直接代理奖励
								 tAccount.update();
								 incomeRecord.setEndStatus((short)2);
								 incomeRecord.update();
								 TbMsg msg2=new TbMsg(
										 incomeRecord.getBeneficiary()//会员
		   	     						 	,"您获得了收益:"+incomeRecord.getIncome()
		   	     						 	,new Date()//时间
		   	     							);
		   	                		msg2.save();
							}
					}
				}
				
				 Configur configur=Configur.where.status((short)1).get();
				 TbOrderInvoies orderInvoies=new TbOrderInvoies(
						    order.getNo()//订单编号
						 	,order.getOrderType()//来源
						 	,order.getMerchant()//品牌商
						 	,order.getMember()//购买人
						 	,order.getTotalSum()//订单总金额
						 	,order.getActualPay()//实际支付金额
						 	,order.getProductFree()//余额抵扣金额
						 	,order.getCouponFree()//优惠卷抵扣金额
						 	,0.0//平台收益
						 	,0.0//普通间接收益
						 	,0.0//普通直接收益
						 	,0.0//代理间接收益
						 	,0.0//代理直接收益
						 	,0.0//合伙人收益
						 	,0.0//配送商收益
						 	,0.0//经销商收益
						 	,0.0
						 	,new Date()//添加时间
						 );
				    orderInvoies=orderInvoies.save();
				    if (member.gettTop()!=null&&!member.gettTop().equals("")) {
				    	Agent agent=Agent.where.member(Long.parseLong(member.gettTop())).merchant(order.getMerchant()).get();
				    	if (agent!=null) {
				    		orderInvoies.setTboiDlZj(Arith.round(Arith.mul(gj, parameter.getpDlZj()), 2));
						}else {
							orderInvoies.setTboiPtZj(Arith.round(Arith.mul(gj, parameter.getpPtZj()), 2));
						}
					}
				    if (member.gettToptop()!=null&&!member.gettToptop().equals("")) {
				    	Agent agent=Agent.where.member(Long.parseLong(member.gettToptop())).merchant(order.getMerchant()).get();
				    	if (agent!=null) {
				    		orderInvoies.setTboiDlJj(Arith.round(Arith.mul(gj, parameter.getpDlJj()), 2));
						}else {
							orderInvoies.setTboiPtJj(Arith.round(Arith.mul(gj, parameter.getpPtJj()), 2));
						}
					}
				    if (order.getDistributor()!=null) {
				    	Distributor distributor=Distributor.where.id(order.getDistributor()).get();
				    	if (distributor!=null) {
				    		DistributorIncome distributorIncome=DistributorIncome.where.directOrder(order.getId()).distributor(distributor.getId()).get();
				    		if (distributorIncome!=null&&distributorIncome.getOrderStatus()==(short)1) {
								orderInvoies.setTboiPsSy(Arith.round(gj*parameter.getpPsYj(), 2));
								distributorIncome.setOrderStatus((short)2);
								 distributorIncome.update();
											 Account tAccount=Account.where.member(distributor.getMember()).get();
											 if (tAccount!=null) {
												 tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), gj*parameter.getpPsYj()), 2));//直接代理奖励
												 tAccount.update();
												 TbMsg msg2=new TbMsg(
														 distributor.getMember()//会员
						   	     						 	,"您获得了收益:"+gj*parameter.getpPsYj()
						   	     						 	,new Date()//时间
						   	     							);
						   	                		msg2.save();
											}
											
								}
				    	  	
				    		BindingDistributor bindingDistributor=BindingDistributor.where.merchant(order.getMerchant()).distributor(distributor.getId()).get();
							if (bindingDistributor!=null&&bindingDistributor.getBindingdJxsh()!=null) {
								TbJxsh jxs=TbJxsh.where.tbjId(bindingDistributor.getBindingdJxsh()).get();
								if (jxs!=null) {
									order.setJxs(jxs.getTbjName());
									order.update();
								}
							 orderInvoies.setTboiJxsSy(((Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()))*0.08)/0.18);
							 List<OrderDetails> orderDetails=OrderDetails.where.orders(order.getId()).list(-1);
							 List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
								for (OrderDetails orderDetails2 : orderDetails) {
									Map<String, Object> map=new HashMap<String, Object>();
									map.put("goodsNumber",orderDetails2.getGoodsNumber());
									map.put("name", orderDetails2.getName());
									map.put("price", orderDetails2.getPrice());
									map.put("number", orderDetails2.getNumber());
									map.put("status", orderDetails2.getStatus$());
									list.add(map);
								}	
							 TbJxshIncome jxshIncome=new TbJxshIncome(
										order.getMerchant()
										,bindingDistributor.getBindingdJxsh()//经销商
										,order.getJxs()
									 	,order.getId()//订单编号
									 	,order.getAddTime()
										,order.getConsigneeName()
										,order.getDistributor$()
										,order.getOrderType()
										,JSON.toJSONString(list)
									 	,((Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()))*0.08)/0.18//收益金额
									 	,new Date()
										);
								jxshIncome.save();
							}
				    	}
					}
					
				 TbPartners partners=TbPartners.where.tbpJiedao(order.getStreet()).get();
				 Region region=Region.where.id(order.getStreet()).get();
				 if (partners!=null) {
					 Member member2=Member.where.uid(partners.getTbpMember()).get();
					 orderInvoies.setTboiHhrSy(Arith.round(gj*parameter.getpHhrYj(), 2));
					 TbPartnerIncome partnerIncome=new TbPartnerIncome(
							     order.getMerchant()//品牌
							 	,member2.getUid()//会员
							 	,order.getNo()
								,order.getOrderType()
							 	,member2.getNickName()
							 	,member.getHeader()//头像
							 	,member.getNickName()//昵称
							 	,region.getName()//街道
							 	,region.get$parent().getFullName()
							 	,new Date()//下单时间
							    ,Arith.round(gj*parameter.getpHhrYj(), 2)//收益金额
							 );
					 partnerIncome.save();
					 Account tAccount=Account.where.member(member2.getUid()).get();
					 if (tAccount!=null) {
						 tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), Arith.round(gj*parameter.getpHhrYj(), 2)), 2));//直接代理奖励
						 tAccount.update();
						 TbMsg msg2=new TbMsg(
								 member2.getUid()//会员
   	     						 	,"您获得了收益:"+Arith.round(gj*parameter.getpHhrYj(), 2)
   	     						 	,new Date()//时间
   	     							);
   	                		msg2.save();
					}
				}
				 orderInvoies.setTboiSySy(Arith.round(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(
						                                                         order.getTotalSum(), order.getDispatFee()),
						                                                         orderInvoies.getTboiPtSy()),
																				 orderInvoies.getTboiPtJj()),
																				 orderInvoies.getTboiPtZj()),
																				 orderInvoies.getTboiDlJj()),
																				 orderInvoies.getTboiDlZj()),
																				 orderInvoies.getTboiPsSy()),
																				 orderInvoies.getTboiHhrSy()),
																				 orderInvoies.getTboiJxsSy()), 2));
				orderInvoies.update(); 
//				BrandAccount brandAccount=BrandAccount.where.brand(order.getMerchant()).get();
//				if (brandAccount==null) {
//					BrandAccount bccount=new BrandAccount(
//							order.getMerchant()//所属品牌 [非空]
//						 	,orderInvoies.getTboiSySy()//总金额
//						 	,orderInvoies.getTboiSySy()//累计收益
//						 	,0.0//累计提现
//						 	,new Date()//修改时间 [非空]
//						 	,new Date()//添加时间 [非空]
//						 	,(short)1//状态 [非空]
//							);
//					bccount.save();
//				}else {
//					brandAccount.setMoney(Arith.round(Arith.add(brandAccount.getMoney(), orderInvoies.getTboiSySy()), 2));
//					brandAccount.setlSmoney(Arith.round(Arith.add(brandAccount.getlSmoney(), orderInvoies.getTboiSySy()), 2));
//					brandAccount.update();
//				}
				
				
				
			}
		    protocol.set("type", 1);
			protocol.set("msg", "收货成功");
		return protocol;
	}
	/**
	 * 会员申请退款
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/returnMoney.do")
	public @title("会员申请退款") Protocol returnMoney(
			@title("订单ID") Long id,
			@title("退款理由") String liyou,
			@title("formId") String formId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder order=DirectOrder.where.id(id).get();
		if (order!=null) {
			order.setMeRefundMoney(liyou);
			order.setRefundStatus((short)1);
			order.setProcessor((short)0);
			order.setDirectoFormid(formId);
			order.setStatus((short)5);
			order.update();
			protocol.set("type", 1);
			protocol.set("msg", "已提交!请等待处理");
		}else {
			protocol.set("type", 2);
			protocol.set("msg", "订单不存在");
		}
		return protocol;
	}
	/**
	 * 会员投诉订单
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/tSOrder.do")
	public @title("会员投诉订单") Protocol tSOrder(
			@title("订单ID") Long id,
			@title("投诉理由") String liyou
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder order=DirectOrder.where.id(id).get();
		if (order!=null) {
			order.setComplaint(liyou);
			order.setDealted((short)1);
			order.setProcessor((short)0);
			order.setStatus((short)5);
			order.update();
			
			protocol.set("type", 1);
			protocol.set("msg", "投诉成功!请等待处理");
		}else {
			protocol.set("type", 2);
			protocol.set("msg", "订单不存在");
		}
		return protocol;
	}
	/**
	 * 会员订单列表
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/memberOrders.do")
	public @title("会员订单列表") Protocol memberOrders(
			@title("页码") Integer pageNo
			,@title("个数") Integer pageSize
			,@title("品牌编号") Long banrdId
			,@title("订单类型") Short type
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder.M where = DirectOrder.where.member(member.getId()).merchant(banrdId).desc("add_time");
		if(type!=(short)0){
			where.status(type);
		}else {
			where.statusIn("1,2,3,4,5,6");
		}
		protocol.setPage(where.page(Utils.or(pageNo,0), Utils.or(pageSize,20)), new Protocol.BeanFormat<DirectOrder>(){
			@Override
			public Map format(DirectOrder t) {
				Map json = t.toJSON();
				List<OrderDetails> orderDetails=OrderDetails.where.orders(t.getId()).list(-1);
				Double sum=0.0;
				Integer counts=0;
				if(orderDetails.size()>0){
					for (OrderDetails orderDetails2 : orderDetails) {
						sum=Arith.round(Arith.add(sum, Arith.mul(orderDetails2.getNumber(), orderDetails2.getPrice())), 2);
						counts=counts+orderDetails2.getNumber();
					}
				}
				List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
				if (orderDetails.size()>0) {
					for (OrderDetails oDetails : orderDetails) {
						Map<String, Object> map=new HashMap<String, Object>();
						map.put("id", oDetails.getId());
						map.put("name", oDetails.getName());
						map.put("orders", oDetails.getOrders());
						map.put("goodsNumber", oDetails.getGoodsNumber());
						map.put("img", oDetails.getImg());
						map.put("price", oDetails.getPrice());
						map.put("number", oDetails.getNumber());
						map.put("attributes", oDetails.getAttributes());
						map.put("distributorIncome", oDetails.getDistributorIncome());
						map.put("updateTime", oDetails.getUpdateTime$());
						map.put("addTime", oDetails.getAddTime$());
						map.put("status", oDetails.getStatus());
						list.add(map);
					}
				}
				json.put("child", list);
				if(t.getDistributor()!=null){
					Distributor distributor=Distributor.where.id(t.getDistributor()).get();
					json.put("phone", distributor.getMobile()!=null&&!distributor.getMobile().equals("")?distributor.getMobile():"");
				}else {
					Merchant merchant=Merchant.where.id(t.getMerchant()).get();
					json.put("phone", merchant.getContactNumber()!=null&&!merchant.getContactNumber().equals("")?merchant.getContactNumber():"");
				}
				
				json.put("sum", sum);
				json.put("counts", counts);
				return json;
			}
		});
		return protocol;
	}
	/**
	 * 会员余额提货确认订单。
	 * @return
	 */
	@RequestMapping("/api/orders/yEConfirmOrder.do")
	public @title("会员余额提货确认订单")  Protocol yEConfirmOrder(
			@title("网点编号") Long dotId,
			@title("地址编号") Long adressId,
			@title("订单编号") Long orderId,
			@title("配送费") Double pfee,
			@title("配送方式") Short pType,
			@title("备注") String remarks,
			@title("支付协议") Short xie
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder directOrder=DirectOrder.where.id(orderId).get();
		UserAddress userAddress=UserAddress.where.id(adressId).get();
		Region region=Region.where.id(userAddress.getAddress()).get();
		directOrder.setAddress(userAddress.getFullAddress()+" "+userAddress.getDetailAddress());
		directOrder.setConsigneeName(userAddress.getRealName());
		directOrder.setStreet(region.getId());
		directOrder.setReceivingTelephoneNumber(userAddress.getMobile());
		directOrder.setGender(userAddress.getSex());
		directOrder.setLatitude(userAddress.getLatitude());
		directOrder.setLongitude(userAddress.getLongitude());
		directOrder.setDx(directOrder.getTotalSum());
		directOrder.setRemarks(remarks);
		if (pType==(short)2) {
			List<BindingDistributor> bindingDistributors=BindingDistributor.where.bindingState((short)1).merchant(directOrder.getMerchant()).locations(userAddress.getCityOrigin()).list(10000);
			double jl=0; Long thisId=null; Distributor thisDot=null;
			if (bindingDistributors.size()>0) {
				for (BindingDistributor bindingDistributor : bindingDistributors) {
					Distributor dot=Distributor.where.id(bindingDistributor.getDistributor()).get();
					if (dot!=null) {
						String aString=userAddress.getLatitude()+","+userAddress.getLongitude();
						String bString=dot.getLatitude()+","+dot.getLongitude();
						double lj=MapHelper.GetPointDistance(aString, bString);	
						if (jl==(double)0) {
						   jl=lj;
						   thisDot=dot;
						}else {
							if (lj<jl) {
								jl=lj;
								 thisDot=dot;
							}
						}
					}
				}
			}
			if (thisDot!=null) {
				directOrder.setsType((short)1);
				directOrder.setDistributor(thisDot.getId());
			}else {
				directOrder.setsType((short)2);
				pfee=0.0;
			}
			directOrder.setDistributionMode((short)2);
			directOrder.setDispatFee(pfee);
			directOrder.setStatus((short)2);
			//protocol.set("red", redPacket.toJSON());
		}else {
			Distributor dot=Distributor.where.id(dotId).get();
			directOrder.setDistributor(dot.getId());
			directOrder.setsType((short)1);
			directOrder.setSelfAddress(dot.getCoordinateAddress());
			directOrder.setDistributionMode((short)1);
			directOrder.setDispatFee(0.0);
			directOrder.setStatus((short)2);
		}
		directOrder.setAgreement(xie);
		directOrder.update();
		if (directOrder.getUseProductVouchers()!=null&&!directOrder.getUseProductVouchers().equals("")) {
     			JSONArray jsonArray=JSON.parseArray(directOrder.getUseProductVouchers());
     			if (jsonArray.size()>0) {
     				for (int i = 0; i < jsonArray.size(); i++) {
     					JSONObject jsonObject=jsonArray.getJSONObject(i);
     					Product product=Product.where.id(jsonObject.getLong("id")).get();
     					product.setNumber(product.getNumber()-jsonObject.getInteger("count"));
     					product.update();
     				}
     			}
     		}
		protocol.set("msg", "提交成功");
		protocol.set("type", "1");
		return protocol;
	}
	/**
	 * 会员余额提货并支付配送费确认订单。
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/api/orders/yaoFreeConfirmOrder.do")
	public @title("会员余额提货并支付配送费确认订单")  Protocol yaoFreeConfirmOrder(
			@title("网点编号") Long dotId,
			@title("地址编号") Long adressId,
			@title("订单编号") Long orderId,
			@title("配送费") Double pfee,
			@title("配送方式") Short pType,
			@title("备注") String remarks,
			@title("支付协议") Short xie
			) throws Exception{
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder directOrder=DirectOrder.where.id(orderId).get();
		UserAddress userAddress=UserAddress.where.id(adressId).get();
		String orderNo=new Date().getTime()*3+"-"+member.getId();
		Region region=Region.where.id(userAddress.getAddress()).get();
		directOrder.setNo(orderNo);
		directOrder.setAddress(userAddress.getFullAddress()+" "+userAddress.getDetailAddress());
		directOrder.setConsigneeName(userAddress.getRealName());
		directOrder.setReceivingTelephoneNumber(userAddress.getMobile());
		directOrder.setGender(userAddress.getSex());
		directOrder.setStreet(region.getId());
		directOrder.setDx(directOrder.getTotalSum());
		directOrder.setLatitude(userAddress.getLatitude());
		directOrder.setLongitude(userAddress.getLongitude());
		directOrder.setRemarks(remarks);
			List<BindingDistributor> bindingDistributors=BindingDistributor.where.bindingState((short)1).merchant(directOrder.getMerchant()).locations(userAddress.getCityOrigin()).list(10000);
			double jl=0; Long thisId=null; Distributor thisDot=null;
			if (bindingDistributors.size()>0) {
				for (BindingDistributor bindingDistributor : bindingDistributors) {
					Distributor dot=Distributor.where.id(bindingDistributor.getDistributor()).get();
					if (dot!=null) {
						String aString=userAddress.getLatitude()+","+userAddress.getLongitude();
						String bString=dot.getLatitude()+","+dot.getLongitude();
						double lj=MapHelper.GetPointDistance(aString, bString);	
						if (jl==(double)0) {
						   jl=lj;
						   thisDot=dot;
						}else {
							if (lj<jl) {
								jl=lj;
								 thisDot=dot;
							}
						}
					}
				}
			}
			if (thisDot!=null) {
				directOrder.setsType((short)1);
				directOrder.setDistributor(thisDot.getId());
			}else {
				directOrder.setsType((short)2);
			}
			directOrder.setDistributionMode((short)2);
			directOrder.setDispatFee(pfee);
			Parameter parameter=Parameter.where.merchant(directOrder.getMerchant()).get();
			directOrder.setDistributorIncome(Arith.round(Arith.mul(directOrder.getActualPay(), parameter.getpPsYj()), 2));
			directOrder.setStatus((short)1);
			directOrder.setPaysStatus((short)0);
			directOrder.setAgreement(xie);
			directOrder.update();
			String pay_url=Utils.config("conf.wxpayurl");
			String notify_url=Utils.config("conf.host")+"/api/orders/tiPsFreeModify.wx";//回调接口地址
	        //生成的随机字符串  
	    	 String nonce_str = IpUtil.getRandomStringByLength(32); 
	        //商品名称  
	        String body = "支付配送费";  
	        //获取客户端的ip地址  
	        String spbill_create_ip = IpUtil.getIpAddr(Utils.getServletRequest());
	        System.out.println("真实IP地址"+spbill_create_ip);
	        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
	        String money=decimalFormat.format(pfee*100);
	      //String spbill_create_ip = "127.0.0.1";
	        //组装参数，用户生成统一下单接口的签名  
	        Map<String, String> packageParams = new HashMap<String, String>();  
	        packageParams.put("appid", Utils.config("wx.mp1.appid"));  
	        packageParams.put("mch_id", Utils.config("wx.mch1.id"));  
	        packageParams.put("nonce_str", nonce_str);  
	        packageParams.put("body", body);  
	        packageParams.put("out_trade_no", directOrder.getNo());//商户订单号  
	        packageParams.put("total_fee", money);//支付金额，这边需要转成字符串类型，否则后面的签名会失败  
	        packageParams.put("spbill_create_ip", spbill_create_ip);  
	        packageParams.put("notify_url", notify_url);//支付成功后的回调地址  
	        packageParams.put("trade_type", "JSAPI");//支付方式  
	        packageParams.put("openid", member.getOpenid());  
	             
	            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串   
	          
	            //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口  
	            String mysign = PayUtil.sign(prestr, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
	          
	        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去  
	        String xml = "<xml>" + "<appid>" +Utils.config("wx.mp1.appid") + "</appid>"   
	                + "<body><![CDATA[" + body + "]]></body>"   
	                + "<mch_id>" +  Utils.config("wx.mch1.id") + "</mch_id>"   
	                + "<nonce_str>" + nonce_str + "</nonce_str>"   
	                + "<notify_url>" + notify_url + "</notify_url>"   
	                + "<openid>" + member.getOpenid() + "</openid>"   
	                + "<out_trade_no>" + directOrder.getNo() + "</out_trade_no>"   
	                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"   
	                + "<total_fee>" + money + "</total_fee>"  
	                + "<trade_type>" + "JSAPI" + "</trade_type>"   
	                + "<sign>" + mysign + "</sign>"  
	                + "</xml>";  
	          
	        System.out.println("调试模式_统一下单接口 请求XML数据：" + xml);  
	        //调用统一下单接口，并接受返回的结果  
	        String result = PayUtil.httpRequest(pay_url, "POST", xml);  
	        System.out.println("调试模式_统一下单接口 返回XML数据：" + result);  
	        // 将解析结果存储在HashMap中     
	        Map map = PayUtil.doXMLParse(result);  
	        String return_code = (String) map.get("return_code");//返回状态码  
	          
	        System.out.println("调试模式_统一下F返回状态" + return_code);  
	        if(return_code.equals("SUCCESS")){     
	            String prepay_id = (String) map.get("prepay_id");//返回的预付单信息     
	            protocol.set("nonceStr", nonce_str);  
	            protocol.set("package", "prepay_id=" + prepay_id);  
	            Long timeStamp = System.currentTimeMillis() / 1000;     
	            protocol.set("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误  
	            //拼接签名需要的参数  
	            String stringSignTemp = "appId=" + Utils.config("wx.mp1.appid") + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;     
	            //再次签名，这个签名用于小程序端调用wx.requesetPayment方法  
	            String paySign = PayUtil.sign(stringSignTemp, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
	            protocol.set("type", 1); 
	            protocol.set("paySign", paySign);  
	            protocol.set("appid", Utils.config("wx.mp1.appid")); 
	            protocol.setSuccess(true);
	        }else {
	        	protocol.setSuccess(false);
	        	protocol.setMessage("支付失败");
			}
			protocol.set("msg", "提交成功");
			protocol.set("type", "1");
			return protocol;
			//protocol.set("red", redPacket.toJSON());
	}
	/**
	 * 会员余额提货并支付配送费回调
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/tiPsFreeModify.wx")
	public @title("会员余额提货并支付配送费回调") void tiPsFreeModify(
			HttpServletRequest request,HttpServletResponse response
			)throws Exception{
		 BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
		  String line = null;  
	        StringBuilder sb = new StringBuilder();  
	        while((line = br.readLine()) != null){  
	            sb.append(line);  
	        }  
	        //sb为微信返回的xml  
	        String notityXml = sb.toString();  
	        String resXml = "";  
	        System.out.println("接收到的报文：是" + notityXml);  
	      
	        Map map = PayUtil.doXMLParse(notityXml);  
	         // System.out.println("返回ID"+map.get("out_trade_no"));
	        //  System.out.println("返回成功"+ map.get("return_code"));
	        if (map!=null){
	        	   String returnCode = (String) map.get("return_code");  
	   	        if("SUCCESS".equals(returnCode)){  
//	   	            //验证签名是否正确  
//	   	            if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){  
	   	                /**此处添加自己的业务逻辑代码start**/  
	   	                  String out_trade_no=(String) map.get("out_trade_no");
	   	                  DirectOrder order=DirectOrder.where.no(out_trade_no).get();
	   	                  if (order.getStatus()==(short)1) {
	   	                	  order.setStatus((short)2);
			   	                order.setPaysStatus((short)1);
			   	                order.setActualPay(order.getDispatFee());
		   	                    order.update();//修改订单
		   	                 if (order.getUseProductVouchers()!=null&&!order.getUseProductVouchers().equals("")) {
		 	   	      			JSONArray jsonArray=JSON.parseArray(order.getUseProductVouchers());
		 	   	      			if (jsonArray.size()>0) {
		 	   	      				for (int i = 0; i < jsonArray.size(); i++) {
		 	   	      					JSONObject jsonObject=jsonArray.getJSONObject(i);
		 	   	      					Product product=Product.where.id(jsonObject.getLong("id")).get();
		 	   	      					product.setNumber(product.getNumber()-jsonObject.getInteger("count"));
		 	   	      					product.update();
		 	   	      				}
		 	   	      			}
		 	   	      		}
		   	                /**此处添加自己的业务逻辑代码end**/  
		   	                //通知微信服务器已经支付成功  
		   	                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
		   	                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
		   	        
						}
	   	                  //    }  
	   	        }else{  
	   	            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
	   	            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
	   	        }  
	        }
	     
	      //  System.out.println(resXml);  
	       // System.out.println("微信支付回调数据结束");  
	  
	  
	        BufferedOutputStream out = new BufferedOutputStream(  
	                response.getOutputStream());  
	        out.write(resXml.getBytes());  
	        out.flush();  
	        out.close(); 
	}
	/**
	 * 会员直接购买回调
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/zhiGouModify.wx")
	public @title("会员直接购买回调") void zhiGouModify(
			HttpServletRequest request,HttpServletResponse response
			)throws Exception{
		 BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
		  String line = null;  
	        StringBuilder sb = new StringBuilder();  
	        while((line = br.readLine()) != null){  
	            sb.append(line);  
	        }  
	        //sb为微信返回的xml  
	        String notityXml = sb.toString();  
	        String resXml = "";  
	        System.out.println("接收到的报文：是" + notityXml);  
	      
	        Map map = PayUtil.doXMLParse(notityXml);  
	         // System.out.println("返回ID"+map.get("out_trade_no"));
	        //  System.out.println("返回成功"+ map.get("return_code"));
	        if (map!=null){
	        	   String returnCode = (String) map.get("return_code");  
	        	   System.out.println("是否成功++++++++++"+"shifouchenggong"+returnCode);
	   	        if("SUCCESS".equals(returnCode)){  
	   	         System.out.println("是否进来++++++++++"+"是否进来"+returnCode);
//	   	            //验证签名是否正确  
//	   	            if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){  
	   	                /**此处添加自己的业务逻辑代码start**/  
	   	                  String out_trade_no=(String) map.get("out_trade_no");
	   	                  DirectOrder order=DirectOrder.where.no(out_trade_no).get();
	   	                  if (order.getStatus()==(short)1) {
	   	                	 System.out.println("是否找到订单++++++++++"+"是否找到订单"+returnCode); 
	   	                	  
	   	                   order.setStatus((short)2);
		   	                order.setPaysStatus((short)1);
	   	                    order.update();//修改订单
	   	            if (order.getCoupon()!=null&&order.getCoupon()>0) {
	   	      			Coupon coupon=Coupon.where.id(order.getCoupon()).member(order.getMember()).get();
	   	      			 coupon.setUseStatus((short)2);
	   	      	    	 coupon.update();//优惠卷使用了  改成已使用状态。
	   	      		}
	   	      		if (order.getUseProductVouchers()!=null&&!order.getUseProductVouchers().equals("")) {
	   	      			JSONArray jsonArray=JSON.parseArray(order.getUseProductVouchers());
	   	      			if (jsonArray.size()>0) {
	   	      				for (int i = 0; i < jsonArray.size(); i++) {
	   	      					JSONObject jsonObject=jsonArray.getJSONObject(i);
	   	      					Product product=Product.where.id(jsonObject.getLong("id")).get();
	   	      					product.setNumber(product.getNumber()-jsonObject.getInteger("count"));
	   	      					product.update();
	   	      				}
	   	      			}
	   	      		}
		   	             if (Arith.round(Arith.sub(order.getActualPay(), order.getDispatFee()), 2)>=1) {
			                Parameter parameter=Parameter.where.merchant(order.getMerchant()).get();
	   	                 Member member=Member.where.uid(order.getMember()).get();
	   	                 
	   	              System.out.println("有用户编号++++++++++"+"youyonghubianhao"+order.getMember());
	   	                  if(member.gettTop()!=null&&!member.gettTop().equals("")){//
	   	                	  System.out.println("有上级++++++++++"+"youshangji");
	   	                	 Member member2=Member.where.uid(Long.parseLong(member.gettTop())).get();//上级
	   	                	Agent agent=Agent.where.member(member2.getId()).merchant(order.getMerchant()).status((short)1).get();
	   	                	TbPartners agentas=TbPartners.where.tbpMember(member2.getId()).tbpBrand(order.getMerchant()).tbpPayCard((short)2).get();
	   	                 if (agent!=null||agentas!=null) {//代理商
	   	                  System.out.println("有代理++++++++++"+"youdaili");
	   	                		IncomeRecord incomeRecord=new IncomeRecord(
	   	                				agentas!=null?(short)3:(short)2
	   	                				,(short)1//来源
	   	                			 	,(short)1//收益类型
	   	                			 	,Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpDlZj()),2)//贡献收益
	   	                			 	,member.getHeader()//头像
	   	                			 	,member.getNickName()//姓名
	   	                			 	,member.getNickName()
   	                			 	,member2.getNickName()
	   	                			 	,member.getId()//贡献人
	   	                			 	,member2.getId()//收益人
	   	                			 	,order.getNo()//订单编号
	   	                			 	,order.getMerchant()//品牌信息
	   	                			 	,(short)1//结算情况
	   	                			 	,new Date()//修改时间 [非空]
	   	                			 	,new Date()//添加时间 [非空]
	   	                			 	,(short)1//状态 [非空]
	   	                			 	);
	   	                		incomeRecord.save();
								}else {//普通分销员
									 System.out.println("普通分销++++++++++"+"putongfenxiao");
									IncomeRecord incomeRecord=new IncomeRecord(
											(short)1
											,(short)1//来源
		   	                			 	,(short)1//收益类型
		   	                			 	,Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpPtZj()),2)//贡献收益
		   	                			 	,member.getHeader()//头像
		   	                			 	,member.getNickName()//姓名
		   	                			 	,member.getNickName()
   	                			 	,member2.getNickName()
		   	                			 	,member.getId()//贡献人
		   	                			 	,member2.getId()//收益人
		   	                			 	,order.getNo()//订单编号
		   	                			 	,order.getMerchant()//品牌信息
		   	                			 	,(short)1//结算情况
		   	                			 	,new Date()//修改时间 [非空]
		   	                			 	,new Date()//添加时间 [非空]
		   	                			 	,(short)1//状态 [非空]
		   	                			 	);
		   	                		incomeRecord.save();
								}
	   	                	 if (member2.gettTop()!=null&&!member2.gettTop().equals("")) {
	   	                		System.out.println("有上上级++++++++++"+"youshangshangji");
	   	                		 Member member3=Member.where.uid(Long.parseLong(member2.gettTop())).get();//上上级
	   	                		Agent agent2=Agent.where.member(member3.getId()).merchant(order.getMerchant()).status((short)1).get();
	   	                		TbPartners agentasds=TbPartners.where.tbpMember(member3.getId()).tbpBrand(order.getMerchant()).tbpPayCard((short)2).get();
	   	   	                 if (agent2!=null||agentasds!=null) {//代理商
		   	                		IncomeRecord incomeRecord=new IncomeRecord(
		   	                				agentasds!=null?(short)3:(short)2
		   	                				,(short)1//来源
		   	                			 	,(short)2//收益类型
		   	                			 	,Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpDlJj()),2)//贡献收益
		   	                			 	,member.getHeader()//头像
		   	                			 	,member.getNickName()//姓名
		   	                			 	,member.getNickName()
   	                			 	,member3.getNickName()
		   	                			 	,member.getId()//贡献人
		   	                			 	,member3.getId()//收益人
		   	                			 	,order.getNo()//订单编号
		   	                			 	,order.getMerchant()//品牌信息
		   	                			 	,(short)1//结算情况
		   	                			 	,new Date()//修改时间 [非空]
		   	                			 	,new Date()//添加时间 [非空]
		   	                			 	,(short)1//状态 [非空]
		   	                			 	);
		   	                		incomeRecord.save();
									}else {//普通分销员直接奖励
										IncomeRecord incomeRecord=new IncomeRecord(
												(short)1
			   	                				,(short)1//来源
			   	                			 	,(short)2//收益类型
			   	                			 	,Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpPtJj()),2)//贡献收益
			   	                			 	,member.getHeader()//头像
			   	                			 	,member.getNickName()//姓名
			   	                			 	,member.getNickName()
   	                			 	,member3.getNickName()
			   	                			 	,member.getId()//贡献人
			   	                			 	,member3.getId()//收益人
			   	                			 	,order.getNo()//订单编号
			   	                			 	,order.getMerchant()//品牌信息
			   	                			 	,(short)1//结算情况
			   	                			 	,new Date()//修改时间 [非空]
			   	                			 	,new Date()//添加时间 [非空]
			   	                			 	,(short)1//状态 [非空]
			   	                			 	);
			   	                		incomeRecord.save();
									}
							}
	   	                  }
	   	                  
	   	                  
	   	                  
		   	             }
	   	                /**此处添加自己的业务逻辑代码end**/  
	   	                //通知微信服务器已经支付成功  
	   	                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
	   	                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
						}
	   	            
	   	        //    }  
	   	        }else{  
	   	            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
	   	            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
	   	        }  
	        }
	      //  System.out.println(resXml);  
	       // System.out.println("微信支付回调数据结束");  
	  
	  
	        BufferedOutputStream out = new BufferedOutputStream(  
	                response.getOutputStream());  
	        out.write(resXml.getBytes());  
	        out.flush();  
	        out.close(); 
	}
	/**
	 * 会员直接购买确认订单。
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/api/orders/zhiConfirmOrder.do")
	public @title("会员直接购买确认订单")  Protocol zhiConfirmOrder(
			@title("formId") String formId,
			@title("网点编号") Long dotId,
			@title("地址编号") Long adressId,
			@title("订单编号") Long orderId,
			@title("配送费") Double pfee,
			@title("优惠卷优惠金额") Double ymoney,
			@title("余额抵扣金额") Double yemoney,
			@title("优惠卷编号") Long couponId,
			@title("使用余额编号集") String yeIds,
			@title("实际支付金额") Double realyMoney,
			@title("配送方式") Short pType,
			@title("备注") String remarks,
			@title("支付协议") Short xie
			) throws Exception{
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder directOrder=DirectOrder.where.id(orderId).get();
		UserAddress userAddress=UserAddress.where.id(adressId).get();
		Region region=Region.where.id(userAddress.getAddress()).get();
		directOrder.setNo(member.getUid()+"-"+new Date().getTime());
		directOrder.setCoupon(couponId);
		directOrder.setUseProductVouchers(yeIds);
		Parameter parameter=Parameter.where.merchant(directOrder.getMerchant()).get();
		JSONArray yelistArray=JSON.parseArray(yeIds);
		List<OrderDetails> orderDetails=OrderDetails.where.orders(directOrder.getId()).list(100);
		if (yelistArray.size()>0) {
			for(int i=0;i<yelistArray.size();i++) {
				JSONObject jObject=yelistArray.getJSONObject(i);
				for (OrderDetails orderDetails2 : orderDetails) {
					double aa=orderDetails2.getPrice()*jObject.getInteger("count")*parameter.getpPsYj();
					orderDetails2.setDistributorIncome(Arith.round(aa, 2));
				    orderDetails2.update();
				}
			}
		}
		List<OrderDetails> orderDetails1=OrderDetails.where.orders(directOrder.getId()).list(100);
		if (yelistArray.size()>0) {
			for(int i=0;i<yelistArray.size();i++) {
				JSONObject jObject=yelistArray.getJSONObject(i);
				Long jidLong=jObject.getLong("commodity");
				for (OrderDetails orderDetails2 : orderDetails1) {
					if (orderDetails2.getGoodsNumber()==jidLong) {
						double aa=orderDetails2.getPrice()*jObject.getInteger("count")*0.7*parameter.getpPsYj();
						double bb=(orderDetails2.getNumber()-jObject.getInteger("count"))*orderDetails2.getPrice()*parameter.getpPsYj();
						System.out.println("aa使用余额"+aa);
						System.out.println("aa没有使用余额"+bb);
						orderDetails2.setDistributorIncome(Arith.round(aa+bb, 2));
					    orderDetails2.update();
					}
				}
			}
		}
		List<OrderDetails> orderDetails22=OrderDetails.where.orders(directOrder.getId()).list(100);
		if (couponId!=null) {
			Coupon coupon=Coupon.where.id(couponId).get();
			if (coupon!=null) {
				for (OrderDetails orderDetails2 : orderDetails22) {
					if (orderDetails2.getGoodsNumber()==coupon.getCommodity()) {
						double aa=orderDetails2.getDistributorIncome()-orderDetails2.getPrice()*(coupon.getDiscount()/10)*parameter.getpPsYj();
						orderDetails2.setDistributorIncome(Arith.round(aa, 2));
						orderDetails2.update();
					}
				}
			}
		}
		directOrder.setDirectoFormid(formId);
		directOrder.setStreet(region.getId());
		directOrder.setCouponFree(ymoney);
		directOrder.setProductFree(yemoney);
		directOrder.setActualPay(realyMoney);
		directOrder.setAddress(userAddress.getFullAddress()+" "+userAddress.getDetailAddress());
		directOrder.setConsigneeName(userAddress.getRealName());
		directOrder.setReceivingTelephoneNumber(userAddress.getMobile());
		directOrder.setGender(userAddress.getSex());
		directOrder.setLatitude(userAddress.getLatitude());
		directOrder.setLongitude(userAddress.getLongitude());
		directOrder.setRemarks(remarks);
		directOrder.setDx(yemoney);
		directOrder.setDistributorIncome(Arith.paytype(directOrder.getTotalSum(), pfee, yemoney, parameter.getpPsYj(),ymoney));
		directOrder.update();
		
		if (pType==(short)2) {
			List<BindingDistributor> bindingDistributors=BindingDistributor.where.bindingState((short)1).merchant(directOrder.getMerchant()).locations(userAddress.getCityOrigin()).list(10000);
			double jl=0;  Distributor thisDot=null;
			if (bindingDistributors.size()>0) {
				for (BindingDistributor bindingDistributor : bindingDistributors) {
					Distributor dot=Distributor.where.id(bindingDistributor.getDistributor()).get();
					if (dot!=null) {
						String aString=userAddress.getLatitude()+","+userAddress.getLongitude();
						String bString=dot.getLatitude()+","+dot.getLongitude();
						double lj=MapHelper.GetPointDistance(aString, bString);	
						if (jl==(double)0) {
						   jl=lj;
						   thisDot=dot;
						}else {
							if (lj<jl) {
								jl=lj;
								 thisDot=dot;
							}
						}
					}
				}
			}
			if (thisDot!=null) {
				directOrder.setsType((short)1);
				directOrder.setDistributor(thisDot.getId());
			}else {
				directOrder.setsType((short)2);
			}
			directOrder.setDistributionMode((short)2);
			directOrder.setDispatFee(pfee);
			//protocol.set("red", redPacket.toJSON());
		}else {
			Distributor dot=Distributor.where.id(dotId).get();
			directOrder.setDistributor(dot.getId());
			directOrder.setsType((short)1);
			directOrder.setSelfAddress(dot.getCoordinateAddress());
			directOrder.setDistributionMode((short)1);
			directOrder.setDispatFee(0.0);
		}
		directOrder.setAgreement(xie);
		directOrder.update();
		String pay_url=Utils.config("conf.wxpayurl");
		String notify_url=Utils.config("conf.host")+"/api/orders/zhiGouModify.wx";//回调接口地址
		
        //生成的随机字符串  
    	 String nonce_str = IpUtil.getRandomStringByLength(32); 
        //商品名称  
        String body = "购买商品";  
        //获取客户端的ip地址  
        String spbill_create_ip = IpUtil.getIpAddr(Utils.getServletRequest());
        System.out.println("真实IP地址"+spbill_create_ip);
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        String money=decimalFormat.format((directOrder.getActualPay())*100);
      //String spbill_create_ip = "127.0.0.1";
        //组装参数，用户生成统一下单接口的签名  
        Map<String, String> packageParams = new HashMap<String, String>();  
        packageParams.put("appid", Utils.config("wx.mp1.appid"));  
        packageParams.put("mch_id", Utils.config("wx.mch1.id"));  
        packageParams.put("nonce_str", nonce_str);  
        packageParams.put("body", body);  
        packageParams.put("out_trade_no", directOrder.getNo());//商户订单号  
        packageParams.put("total_fee", money);//支付金额，这边需要转成字符串类型，否则后面的签名会失败  
        packageParams.put("spbill_create_ip", spbill_create_ip);  
        packageParams.put("notify_url", notify_url);//支付成功后的回调地址  
        packageParams.put("trade_type", "JSAPI");//支付方式  
        packageParams.put("openid", member.getOpenid());  
             System.out.println("appid"+ Utils.config("wx.mp1.appid"));
             System.out.println("mch_id"+ Utils.config("wx.mch1.id"));  
             System.out.println("nonce_str"+nonce_str);  
             System.out.println("body"+ body);  
             System.out.println("out_trade_no"+directOrder.getNo());//商户订单号  
             System.out.println("total_fee"+money);//支付金额，这边需要转成字符串类型，否则后面的签名会失败  
             System.out.println("spbill_create_ip"+spbill_create_ip);  
             System.out.println("notify_url"+notify_url);//支付成功后的回调地址  
             System.out.println("trade_type"+"JSAPI");//支付方式  
            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串   
          
            //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口  
            String mysign = PayUtil.sign(prestr, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
          
        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去  
        String xml = "<xml>" + "<appid>" +Utils.config("wx.mp1.appid") + "</appid>"   
                + "<body><![CDATA[" + body + "]]></body>"   
                + "<mch_id>" +  Utils.config("wx.mch1.id") + "</mch_id>"   
                + "<nonce_str>" + nonce_str + "</nonce_str>"   
                + "<notify_url>" + notify_url + "</notify_url>"   
                + "<openid>" + member.getOpenid() + "</openid>"   
                + "<out_trade_no>" + directOrder.getNo() + "</out_trade_no>"   
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"   
                + "<total_fee>" + money + "</total_fee>"  
                + "<trade_type>" + "JSAPI" + "</trade_type>"   
                + "<sign>" + mysign + "</sign>"  
                + "</xml>";  
          
        System.out.println("调试模式_统一下单接口 请求XML数据：" + xml);  
        //调用统一下单接口，并接受返回的结果  
        String result = PayUtil.httpRequest(pay_url, "POST", xml);  
        System.out.println("调试模式_统一下单接口 返回XML数据：" + result);  
        // 将解析结果存储在HashMap中     
        Map map = PayUtil.doXMLParse(result);  
        String return_code = (String) map.get("return_code");//返回状态码  
          
        System.out.println("调试模式_统一下F返回状态" + return_code);  
        if(return_code.equals("SUCCESS")){     
            String prepay_id = (String) map.get("prepay_id");//返回的预付单信息     
            protocol.set("nonceStr", nonce_str);  
            protocol.set("package", "prepay_id=" + prepay_id);  
            Long timeStamp = System.currentTimeMillis() / 1000;     
            protocol.set("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误  
            //拼接签名需要的参数  
            String stringSignTemp = "appId=" + Utils.config("wx.mp1.appid") + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;     
            //再次签名，这个签名用于小程序端调用wx.requesetPayment方法  
            String paySign = PayUtil.sign(stringSignTemp, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
            protocol.set("type", 1);
            protocol.set("paySign", paySign);  
            protocol.set("appid", Utils.config("wx.mp1.appid")); 
            protocol.setSuccess(true);
        }else {
        	protocol.setSuccess(false);
        	protocol.setMessage("支付失败");
		}  
		return protocol;
	}
	/**
	 * 会员直接购买全部抵扣余额确认订单。//已改配送收益
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/api/orders/zhiConfirmOrderFree.do")
	public @title("会员直接购买全部抵扣余额确认订单")  Protocol zhiConfirmOrderFree(
			@title("formId") String formId,
			@title("网点编号") Long dotId,
			@title("订单编号") Long adressId,
			@title("订单编号") Long orderId,
			@title("配送方式") Short pType,
			@title("优惠卷优惠金额") Double ymoney,
			@title("余额抵扣金额") Double yemoney,
			@title("优惠卷编号") Long couponId,
			@title("使用余额编号集") String yeIds,
			@title("备注") String remarks,
			@title("支付协议") Short xie
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder directOrder=DirectOrder.where.id(orderId).get();
		UserAddress userAddress=UserAddress.where.id(adressId).get();
		Region region=Region.where.id(userAddress.getAddress()).get();
		directOrder.setAddress(userAddress.getFullAddress()+" "+userAddress.getDetailAddress());
		directOrder.setConsigneeName(userAddress.getRealName());
		directOrder.setStreet(region.getId());
		directOrder.setReceivingTelephoneNumber(userAddress.getMobile());
		directOrder.setLatitude(userAddress.getLatitude());
		directOrder.setLongitude(userAddress.getLongitude());
		directOrder.setGender(userAddress.getSex());
		directOrder.setRemarks(remarks);
		directOrder.setDirectoFormid(formId);
		directOrder.setActualPay(0.0);
		directOrder.setCoupon(couponId);
		directOrder.setUseProductVouchers(yeIds);
		directOrder.setCouponFree(ymoney);
		directOrder.setProductFree(yemoney);
		directOrder.setDx(yemoney);
		JSONArray yelistArray=JSON.parseArray(yeIds);
		 Parameter parameter=Parameter.where.merchant(directOrder.getMerchant()).get();
		List<OrderDetails> orderDetails=OrderDetails.where.orders(directOrder.getId()).list(100);
		if (yelistArray.size()>0) {
			for(int i=0;i<yelistArray.size();i++) {
				JSONObject jObject=yelistArray.getJSONObject(i);
				for (OrderDetails orderDetails2 : orderDetails) {
					double aa=orderDetails2.getPrice()*jObject.getInteger("count")*parameter.getpPsYj();
					orderDetails2.setDistributorIncome(Arith.round(aa, 2));
				    orderDetails2.update();
				}
			}
		}
		List<OrderDetails> orderDetails1=OrderDetails.where.orders(directOrder.getId()).list(100);
		if (yelistArray.size()>0) {
			for(int i=0;i<yelistArray.size();i++) {
				JSONObject jObject=yelistArray.getJSONObject(i);
				Long jidLong=jObject.getLong("commodity");
				for (OrderDetails orderDetails2 : orderDetails1) {
					if (orderDetails2.getGoodsNumber()==jidLong) {
						double aa=orderDetails2.getPrice()*jObject.getInteger("count")*0.7*parameter.getpPsYj();
						double bb=(orderDetails2.getNumber()-jObject.getInteger("count"))*orderDetails2.getPrice()*parameter.getpPsYj();
						System.out.println("aa使用余额"+aa);
						System.out.println("aa没有使用余额"+bb);
						orderDetails2.setDistributorIncome(Arith.round(aa+bb, 2));
					    orderDetails2.update();
					}
				}
			}
		}
		List<OrderDetails> orderDetails22=OrderDetails.where.orders(directOrder.getId()).list(100);
		if (couponId!=null) {
			Coupon coupon=Coupon.where.id(couponId).get();
			if (coupon!=null) {
				for (OrderDetails orderDetails2 : orderDetails22) {
					if (orderDetails2.getGoodsNumber()==coupon.getCommodity()) {
						double aa=orderDetails2.getDistributorIncome()-orderDetails2.getPrice()*(coupon.getDiscount()/10)*parameter.getpPsYj();
						orderDetails2.setDistributorIncome(Arith.round(aa, 2));
						orderDetails2.update();
					}
				}
			}
		}
		if (pType==(short)2) {
			List<BindingDistributor> bindingDistributors=BindingDistributor.where.bindingState((short)1).merchant(directOrder.getMerchant()).locations(userAddress.getCityOrigin()).list(10000);
			double jl=0; Long thisId=null; Distributor thisDot=null;
			if (bindingDistributors.size()>0) {
				for (BindingDistributor bindingDistributor : bindingDistributors) {
					Distributor dot=Distributor.where.id(bindingDistributor.getDistributor()).get();
					if (dot!=null) {
						String aString=userAddress.getLatitude()+","+userAddress.getLongitude();
						String bString=dot.getLatitude()+","+dot.getLongitude();
						double lj=MapHelper.GetPointDistance(aString, bString);	
						if (jl==(double)0) {
						   jl=lj;
						   thisDot=dot;
						}else {
							if (lj<jl) {
								jl=lj;
								 thisDot=dot;
							}
						}
					}
				}
			}
			if (thisDot!=null) {
				directOrder.setsType((short)1);
				directOrder.setDistributor(thisDot.getId());
			}else {
				directOrder.setsType((short)2);
			}
			directOrder.setDistributionMode((short)2);
			directOrder.setPaysStatus((short)1);
			directOrder.setStatus((short)2);
			//protocol.set("red", redPacket.toJSON());
		}else {
			Distributor dot=Distributor.where.id(dotId).get();
			directOrder.setDistributor(dot.getId());
			directOrder.setsType((short)1);
			directOrder.setSelfAddress(dot.getCoordinateAddress());
			directOrder.setDistributionMode((short)1);
			directOrder.setDispatFee(0.0);
			directOrder.setPaysStatus((short)1);
			directOrder.setStatus((short)2);
		}
		
		directOrder.setDistributorIncome(Arith.round(Arith.mul(directOrder.getActualPay(), parameter.getpPsYj()), 2));
		directOrder.setAgreement(xie);
		directOrder.update();
		if (couponId!=null&&couponId>0) {
			Coupon coupon=Coupon.where.id(couponId).member(member.getId()).get();
			 coupon.setUseStatus((short)2);
	    	 coupon.update();//优惠卷使用了  改成已使用状态。
		}
		if (yeIds!=null&&!yeIds.equals("")) {
			JSONArray jsonArray=JSON.parseArray(yeIds);
			if (jsonArray.size()>0) {
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonObject=jsonArray.getJSONObject(i);
					Product product=Product.where.id(jsonObject.getLong("id")).get();
					product.setNumber(product.getNumber()-jsonObject.getInteger("count"));
					product.update();
				}
			}
		}
		protocol.set("type", 1);
		return protocol;
	}
	/**
	 * 会员余额充值回调
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/orders/chongGouModify.wx")
	public synchronized @title("会员余额充值回调") void chongGouModify(
			HttpServletRequest request,HttpServletResponse response
			)throws Exception{
		 BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
		  String line = null;  
	        StringBuilder sb = new StringBuilder();  
	        while((line = br.readLine()) != null){  
	            sb.append(line);  
	        }  
	        //sb为微信返回的xml  
	        String notityXml = sb.toString();  
	        String resXml = "";  
	        System.out.println("接收到的报文：是" + notityXml);  
	      
	        Map map = PayUtil.doXMLParse(notityXml);  
	         // System.out.println("返回ID"+map.get("out_trade_no"));
	        //  System.out.println("返回成功"+ map.get("return_code"));
	        if (map!=null){
	        	   String returnCode = (String) map.get("return_code");  
	   	        if("SUCCESS".equals(returnCode)){  
//	   	            //验证签名是否正确  
//	   	            if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){  
	   	                /**此处添加自己的业务逻辑代码start**/  
	   	                  String out_trade_no=(String) map.get("out_trade_no");
	   	                  String[] sssStrings=out_trade_no.split("-");
	   	                  
	   	               ProductOrder order=ProductOrder.where.orderNumber(out_trade_no).get();
	   	                   if (order.getPaymentStatus()==(short)0) {
	   	                	order.setPaymentStatus((short)1);
	   	                    order.update();//修改订单
	   	                 Configur configur =Configur.where.get();
	   	              Parameter parameter=Parameter.where.merchant(order.getMerchant()).get();
	   	                 Member member=Member.where.uid(order.getMember()).get();
	   	                 
	   	               List<Details> detailss=order.get$details();
	   	               Double totla=0.0;
	   	               if (detailss.size()>0) {
	   	            	   for (Details details : detailss) {
	   	            		   totla=totla+(Integer.valueOf(details.getChong())+details.getZeng()!=null?Integer.valueOf(details.getZeng()):0)*Double.valueOf(details.getPrice());
	   	            		 Product producta=Product.where.member(member.getId()).merchant(order.getMerchant()).commodity(Long.valueOf(details.getGoods())).get();
							 Commodity commodity=Commodity.where.id(Long.valueOf(details.getGoods())).get();
							  ProductDetails productDetails=new ProductDetails(
										"余额产品充值"//获得方式
									 	,order.getMerchant()//品牌信息
									 	,member.getId()//所属会员
									 	,commodity.getId()//商品信息
									 	,Double.valueOf(details.getPrice())
									 	,Integer.valueOf(details.getChong())+details.getZeng()!=null?Integer.valueOf(details.getZeng()):0//数量
									 	,Integer.valueOf(details.getChong())
									 	,Integer.valueOf(details.getZeng())
									 	,new Date()//获得时间 [非空]
									 	,(short)1//状态 [非空]
										);
								productDetails.save();
								TbBalanceStatistics balanceStatistics=TbBalanceStatistics.where.tbbsBrand(order.getMerchant()).get();
								if (balanceStatistics!=null) {
									balanceStatistics.setTbbsNowMonthBuy(balanceStatistics.getTbbsNowMonthBuy()+Integer.valueOf(details.getChong())+Integer.valueOf(details.getZeng()));
									balanceStatistics.setTbbsNowMonthSurplus(balanceStatistics.getTbbsNowMonthSurplus()+Integer.valueOf(details.getChong())+Integer.valueOf(details.getZeng()));
									balanceStatistics.update();
								}else {
									TbBalanceStatistics statistics=new TbBalanceStatistics(
											order.getMerchant()//品牌
										 	,0//上月余量
										 	,Integer.valueOf(details.getChong())+Integer.valueOf(details.getZeng())//本月购量
										 	,0//本月兑换
										 	,Integer.valueOf(details.getChong())+Integer.valueOf(details.getZeng())//本月剩余
										 	,new Date()//修改时间
											);
									statistics.save();
								}
	   	                	 if (producta!=null) {
	   	                		producta.setNumber(producta.getNumber()+Integer.valueOf(details.getChong())+Integer.valueOf(details.getZeng()));
	   	                		producta.update();
							}else {
								
			   	                  Product product=new Product(
			   	                		details.getName()//名称 [非空]
				   	             	 	,order.getMerchant()//品牌信息
				   	             	 	,member.getUid$()
				   	             	 	,member.getId()//所属会员
				   	             	 	,Long.valueOf(details.getGoods())//商品信息
				   	             	 	,Double.valueOf(details.getPrice())
				   	             	 	,details.getUnit()
				   	             	 	,commodity.getImage()
				   	             	 	,Integer.valueOf(details.getChong())+Integer.valueOf(details.getZeng())//数量
				   	             	 	,0
				   	             	 	,""//规格属性
				   	             	 	,0//预留字段
				   	             	 	,"余额充值"//来源描述
				   	             	 	,getThreeYear()
				   	             	    ,new Date()//修改时间 [非空]
			                			,new Date()//添加时间 [非空]
			                			,(short)1//状态 [非空]
			   	                		  );
			   	               product.save();
							}
						}
	   	            	
					   }
	   	               order.update();
	   	                Double ptjj=0.0;
	   	                Double ptzj=0.0; 
	   	                Double dljj=0.0;
		                Double dlzj=0.0;  
	   	                  if(member.gettTop()!=null&&!member.gettTop().equals("")){//
	   	                	 Member member2=Member.where.uid(Long.parseLong(member.gettTop())).get();//上级
	   	                	Agent agent=Agent.where.member(member2.getId()).merchant(order.getMerchant()).status((short)1).get();
	   	                	TbPartners agentas=TbPartners.where.tbpMember(member2.getId()).tbpBrand(order.getMerchant()).tbpPayCard((short)2).get();
	   	                	Account topAccount=Account.where.member(member2.getUid()).get();
	   	                 if (agent!=null||agentas!=null) {//代理商
	   	                		   dlzj=Arith.round(parameter.getpDlZj()*order.getPayment(), 2);
	   	                		IncomeRecord incomeRecord=new IncomeRecord(
	   	                				agentas!=null?(short)3:(short)2
	   	                				,(short)2//来源
	   	                			 	,(short)1//收益类型
	   	                			 	,Arith.round(parameter.getpDlZj()*order.getPayment(), 2)//贡献收益
	   	                			 	,member.getHeader()//头像
	   	                			 	,member.getNickName()//姓名
	   	                			 	,member.getNickName()
   	                			 	,member2.getNickName()
	   	                			 	,member.getId()//贡献人
	   	                			 	,member2.getId()//收益人
	   	                			 	,order.getOrderNumber()//订单编号
	   	                			 	,order.getMerchant()//品牌信息
	   	                			 	,(short)2//结算情况
	   	                			 	,new Date()//修改时间 [非空]
	   	                			 	,new Date()//添加时间 [非空]
	   	                			 	,(short)1//状态 [非空]
	   	                			 	);
	   	                		incomeRecord.save();
	   	                		topAccount.setMoney(Arith.round(Arith.add(topAccount.getMoney(), Arith.round(parameter.getpDlZj()*order.getPayment(), 2)), 2));//直接代理奖励
	   	                	 TbMsg msg2=new TbMsg(
	   	                			member2.getUid()//会员
	   	     						 	,"您获得了收益:"+Arith.round(parameter.getpDlZj()*order.getPayment(), 2)
	   	     						 	,new Date()//时间
	   	     							);
	   	                		msg2.save();		
	   	                 }else {//分销员直接分销奖励
									ptzj=Arith.round(parameter.getpPtZj()*order.getPayment(), 2);
									IncomeRecord incomeRecord=new IncomeRecord(
											(short)1
		   	                				,(short)2//来源
		   	                			 	,(short)1//收益类型
		   	                			 	,Arith.round(parameter.getpPtZj()*order.getPayment(), 2)//贡献收益
		   	                			 	,member.getHeader()//头像
		   	                			 	,member.getNickName()//姓名
		   	                			 	,member.getNickName()
   	                			 	,member2.getNickName()
		   	                			 	,member.getId()//贡献人
		   	                			 	,member2.getId()//收益人
		   	                			 	,order.getOrderNumber()//订单编号
		   	                			 	,order.getMerchant()//品牌信息
		   	                			 	,(short)2//结算情况
		   	                			 	,new Date()//修改时间 [非空]
		   	                			 	,new Date()//添加时间 [非空]
		   	                			 	,(short)1//状态 [非空]
		   	                			 	);
		   	                		incomeRecord.save();
									topAccount.setMoney(Arith.round(Arith.add(topAccount.getMoney(), Arith.round(parameter.getpPtZj()*order.getPayment(), 2)), 2));//直接分销奖励
									 TbMsg msg2=new TbMsg(
				   	                			member2.getUid()//会员
				   	     						 	,"您获得了收益:"+Arith.round(parameter.getpPtZj()*order.getPayment(), 2)
				   	     						 	,new Date()//时间
				   	     							);
				   	                		msg2.save();			
	   	                 }
	   	                	   topAccount.update();
	   	                	 if (member2.gettTop()!=null&&!member2.gettTop().equals("")) {
	   	                		 Member member3=Member.where.uid(Long.parseLong(member2.gettTop())).get();//上上级
	   	                		Agent agent2=Agent.where.member(member3.getId()).merchant(order.getMerchant()).status((short)1).get();
	   	                		TbPartners agentads=TbPartners.where.tbpMember(member3.getId()).tbpBrand(order.getMerchant()).tbpPayCard((short)2).get();
	   	                		Account topTopAccount=Account.where.member(member3.getUid()).get(); 
		   	                	if (agent2!=null||agentads!=null) {//代理商间接奖励
		   	                		dljj=Arith.round(parameter.getpPtJj()*order.getPayment(), 2);
		   	                		IncomeRecord incomeRecord=new IncomeRecord(
		   	                				agentads!=null?(short)3:(short)2
		   	                				,(short)2//来源
		   	                			 	,(short)2//收益类型
		   	                			 	,Arith.round(parameter.getpPtJj()*order.getPayment(), 2)//贡献收益
		   	                			 	,member.getHeader()//头像
		   	                			 	,member.getNickName()//姓名
		   	                			 	,member.getNickName()
   	                			 	,member3.getNickName()
		   	                			 	,member.getId()//贡献人
		   	                			 	,member3.getId()//收益人
		   	                			 	,order.getOrderNumber()//订单编号
		   	                			 	,order.getMerchant()//品牌信息
		   	                			 	,(short)2//结算情况
		   	                			 	,new Date()//修改时间 [非空]
		   	                			 	,new Date()//添加时间 [非空]
		   	                			 	,(short)1//状态 [非空]
		   	                			 	);
		   	                		incomeRecord.save();
		   	                		topTopAccount.setMoney(Arith.round(Arith.add(topTopAccount.getMoney(), Arith.round(parameter.getpPtJj()*order.getPayment(), 2)), 2));//间接代理奖励
		   	                	 TbMsg msg2=new TbMsg(
			   	                			member3.getUid()//会员
			   	     						 	,"您获得了收益:"+Arith.round(parameter.getpPtJj()*order.getPayment(), 2)
			   	     						 	,new Date()//时间
			   	     							);
			   	                		msg2.save();		
		   	                	}else {//普通分销员间接奖励
										ptjj=Arith.round(parameter.getpDlJj()*order.getPayment(), 2);
										IncomeRecord incomeRecord=new IncomeRecord(
			   	                				(short)1
												,(short)2//来源
			   	                			 	,(short)2//收益类型
			   	                			 	,Arith.round(parameter.getpDlJj()*order.getPayment(), 2)//贡献收益
			   	                			 	,member.getHeader()//头像
			   	                			 	,member.getNickName()//姓名
			   	                			 	,member.getNickName()
   	                			 	,member3.getNickName()
			   	                			 	,member.getId()//贡献人
			   	                			 	,member3.getId()//收益人
			   	                			 	,order.getOrderNumber()//订单编号
			   	                			 	,order.getMerchant()//品牌信息
			   	                			 	,(short)2//结算情况
			   	                			 	,new Date()//修改时间 [非空]
			   	                			 	,new Date()//添加时间 [非空]
			   	                			 	,(short)1//状态 [非空]
			   	                			 	);
			   	                		incomeRecord.save();
			   	                		topTopAccount.setMoney(Arith.round(Arith.add(topTopAccount.getMoney(), Arith.round(parameter.getpDlJj()*order.getPayment(), 2)), 2));//简介分销奖励
			   	                	 TbMsg msg2=new TbMsg(
				   	                			member3.getUid()//会员
				   	     						 	,"您获得了收益:"+Arith.round(parameter.getpDlJj()*order.getPayment(), 2)
				   	     						 	,new Date()//时间
				   	     							);
				   	                		msg2.save();		
		   	                	}
		   	                	topTopAccount.update();
							}
	   	                  }
	   	               TbOrderInvoies  orderInvoies=new TbOrderInvoies(
	   	            		
						    order.getOrderNumber()//订单编号
	    	             	 	,(short)2//来源
	    	             	 	,order.getMerchant()//品牌商
	    	             	 	,order.getMember()//购买人
	    	             	 	,order.getPayment()//订单金额
	    	             	 	,order.getPayment()
	    	             	 	,0.0
	    	             	 	,0.0
	    	             	 	,0.0//平台收益
	    	             	 	,ptjj//普通间接收益
	    	             	 	,ptzj//普通直接收益
	    	             	 	,dljj//代理间接收益
	    	             	 	,dlzj//代理直接收益
	    	             	 	,0.0//合伙人收益
	    	             	 	,0.0//配送商收益
	    	             	 	,0.0//经销商收益
	    	             	 	,0.0//剩余收益
	    	             	 	,new Date()//添加时间
	   	                		 );
	   	                 orderInvoies.save();
	   	              BrandAccount brandAccount=BrandAccount.where.brand(order.getMerchant()).get();
	   				if (brandAccount==null) {
	   					BrandAccount bccount=new BrandAccount(
	   							order.getMerchant()//所属品牌 [非空]
	   						 	,orderInvoies.getTboiSySy()//总金额
	   						 	,orderInvoies.getTboiSySy()//累计收益
	   						 	,0.0//累计提现
	   						 	,new Date()//修改时间 [非空]
	   						 	,new Date()//添加时间 [非空]
	   						 	,(short)1//状态 [非空]
	   							);
	   					bccount.save();
	   				}else {
	   					brandAccount.setMoney(Arith.round(Arith.add(brandAccount.getMoney(), orderInvoies.getTboiSySy()), 2));
	   					brandAccount.setlSmoney(Arith.round(Arith.add(brandAccount.getlSmoney(), orderInvoies.getTboiSySy()), 2));
	   					brandAccount.update();
	   				}
	   	                /**此处添加自己的业务逻辑代码end**/  
	   	                //通知微信服务器已经支付成功  
	   	                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
	   	                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> "; 
						}
	   	                 
	   	        //    }  
	   	        }else{  
	   	            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
	   	            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
	   	        }  
	        }
	     
	      //  System.out.println(resXml);  
	       // System.out.println("微信支付回调数据结束");  
	  
	  
	        BufferedOutputStream out = new BufferedOutputStream(  
	                response.getOutputStream());  
	        out.write(resXml.getBytes());  
	        out.flush();  
	        out.close(); 
	}
	private Date getThreeYear() {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
        c.add(Calendar.YEAR, 3);
        Date y = c.getTime();
		return y;
	}
}
